package com.example.shiwu;

import static com.example.shiwu.util.ContextVariable.DOWN_NAME;
import static com.example.shiwu.util.FileDownUtil.getInternalFilesNew;
import static com.example.shiwu.util.TcpService.TAG;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.shiwu.adapter.ElectrodeRoAdapter;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.BoxElectrodeRo;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.ElectrodeRoVo;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.BoxElectrodeRoService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.BoxElectrodeRoService;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.FileDownUtil;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class SendReceiveListActivity extends AppCompatActivity implements ElectrodeRoAdapter.MyClickListener {

    private CheckBox checkBox, send_items_checkbox;
    private RefreshLayout mRefreshLayout;
    private boolean checkSta = false;
    public TextView title_text, title_seting, did;
    public ImageView title_back;
    private Context myContent;
    private ListView listView;
    private ElectrodeRoAdapter myAdapter;
    private List<Map<String, Object>> listitem;
    private ItemsService itemsService;
    private BoxElectrodeRoService sendService;
    private ArrangeService arrangeService;
    private ArrayList<ElectrodeRoVo> sendLisAll = null;
    private Button expor_btn, send_del_btn;
    private int currentPage = 1;
    private int pageSize = 2;
    private int totalSize = 0;
    private String ids = "";
    private List<Integer> idlis = new ArrayList<Integer>();
    private DatabaseHelper dbHelper;
    private Button allCheak;
    private String[] freqData, modeData, freqFilterData, repeatData, valtageData;
    private BoxElectrodeRoService boxElectrodeRoService;
    List<Object> mNewsList = new ArrayList<>();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.electrode_ro_list);
        myContent = this;
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        //send_items_checkbox = findViewById(R.id.send_items_checkbox);
        // allCheak = findViewById(R.id.allCheak);
        sendLisAll = new ArrayList<ElectrodeRoVo>();
        sendService = new BoxElectrodeRoService();
        arrangeService = new ArrangeService();
        boxElectrodeRoService = new BoxElectrodeRoService();
        allCheak = findViewById(R.id.ele_allCheak);
        send_del_btn = findViewById(R.id.ele_item_del_btn);
        title_text.setText("电极电阻记录");
        Resources res = getResources();
        modeData = res.getStringArray(R.array.modeData);
        freqData = res.getStringArray(R.array.freqData);
        repeatData = res.getStringArray(R.array.repeatCount);
        valtageData = res.getStringArray(R.array.valtageData);
        dbHelper = new DatabaseHelper(this);
        listView = findViewById(R.id.electrode_ro_list_view);
//        title_seting.setText("全选");
//        send_items_checkbox.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (checkSta) {
//                    btnNoList();
//                    title_seting.setText("全选");
//                } else {
//                    btnSelectAllList();
//                    title_seting.setText("全不选");
//                }
//
//            }
//        });
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendReceiveListActivity.this.finish();
            }
        });

        this.getDeviceLisAll();

        send_del_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("——————————————删除——————————————————");
                String ids1 = ids.substring(0, ids.length() - 1);
                List<String> idLis = new ArrayList<>();
                if (ids1.length() > 1) {
                    String[] idLis1 = ids1.split(",");
                    idLis.addAll(Arrays.asList(idLis1));
                } else {
                    idLis.add(ids1);
                }

                if (idLis.size() > 0) {
                    for (int i = 0; i < idLis.size(); i++) {
                        BoxElectrodeRo sen = new BoxElectrodeRo();
                        sen.setId(Integer.parseInt(idLis.get(i)));
                        List<BoxElectrodeRo> svlis = boxElectrodeRoService.getBoxElectrodeRo(sen);
                        if (svlis.size() > 0) {
                            if (idLis.get(i).equals(String.valueOf(svlis.get(0).getId()))) {
                                int sId = svlis.get(0).getId();
                                BoxElectrodeRo sen1 = new BoxElectrodeRo();
                                sen1.setStatus(1);
                                sen1.setId(sId);
                                BoxElectrodeRo sen2 = new BoxElectrodeRo();
                                sen2.setId(sId);
                                Boolean bool = boxElectrodeRoService.updade(sen1, sen2);//先删表数据在删除文件
                                if (bool) {
                                    updataData();
                                    Toast.makeText(myContent, "删除成功！", Toast.LENGTH_SHORT).show();

                                } else {
                                    updataData();
                                    Toast.makeText(myContent, "删除成功！", Toast.LENGTH_SHORT).show();
                                }

                            }

                        }
                    }
                }
            }
        });

        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getItemsDataHeaderPull();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { //上拉加载更多
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getItemsDataFooterPull();
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        expor_btn = findViewById(R.id.ele_item_expor_btn);
        expor_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(ids.length() ==0){
                    return;
                }
                String ids1 = ids.substring(0, ids.length() - 1);
                List<String> idLis = new ArrayList<>();
                if (ids1.length() > 1) {
                    String[] idLis1 = ids1.split(",");
                    idLis.addAll(Arrays.asList(idLis1));
                } else {
                    idLis.add(ids1);
                }
                int count = 0;
                String name = "";
                if (idLis.size() > 0) {
                    for (int i = 0; i < idLis.size(); i++) {
                        BoxElectrodeRo sen = new BoxElectrodeRo();
                        sen.setId(Integer.parseInt(idLis.get(i)));
                        List<BoxElectrodeRo> svlis = boxElectrodeRoService.getBoxElectrodeRo(sen);
                        List<Object> ele_lis = listToArray(svlis);
                        if (svlis.size() > 0) {
                            if (idLis.get(i).equals(String.valueOf(svlis.get(0).getId()))) {
                                int itemId = Integer.parseInt(svlis.get(0).getItemId());
                                String createTime = svlis.get(0).getCreateTime();
                                String createTime1 = createTime.substring(0, 10);
                                List<Items> itlis = itemsService.getItems(new Items(itemId));
                                name = itlis.get(0).getName();
                                String fileName = name + "-" + createTime1 + ".txt";
                                //Boolean bool2 = writeObjectToExternalStorage(myContent,ele_lis,fileName,name);
                                Boolean bool2 = FileDownUtil.saveWithMediaStore(myContent,ele_lis,fileName,name);
                                if (bool2) {
                                    count += 1;
                                }
                            }

                        }
                    }
                }

                if (count == idLis.size()) {
                    Toast.makeText(myContent, "文件已保存到 Download"+"/shiwu/"+name+" 目录", Toast.LENGTH_SHORT).show();
                    //Toast.makeText(myContent, "导出成功！", Toast.LENGTH_SHORT).show();
                } else {
                    //Toast.makeText(myContent, "导出失败！", Toast.LENGTH_SHORT).show();
                    Toast.makeText(myContent, "导出成功！", Toast.LENGTH_SHORT).show();
                }

            }
        });



        Items items = null;
        try {
            items = findSelectItem();
            if (null != items) {
                Device dev = new Device();
                dev.setItemId(String.valueOf(items.getId()));
                int count = sendLisAll.size();
                if (count > 0) {
                    allCheak.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (checkSta) {
                                btnNoList();
                                allCheak.setText("全选");
                            } else {
                                btnSelectAllList();
                                allCheak.setText("全不选");
                            }

                        }
                    });
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private List<Object> listToArray(List<BoxElectrodeRo> boxElectrodeRo){
        for (int i = 0; i < boxElectrodeRo.size(); i++) {
            String boxId = boxElectrodeRo.get(i).getBoxId();
            String boxIdVal = boxId;
            mNewsList.add(boxIdVal+"_1 "+boxIdVal+"_2 = "+boxElectrodeRo.get(i).getOneRo());
            mNewsList.add(boxIdVal+"_2 "+boxIdVal+"_3 = "+boxElectrodeRo.get(i).getTwoRo());
            mNewsList.add(boxIdVal+"_3 "+boxIdVal+"_4 = "+boxElectrodeRo.get(i).getThreeRo());
            mNewsList.add(boxIdVal+"_4 "+boxIdVal+"_5 = "+boxElectrodeRo.get(i).getFourRo());
            mNewsList.add(boxIdVal+"_5 "+boxIdVal+"_6 = "+boxElectrodeRo.get(i).getFiveRo());
            mNewsList.add(boxIdVal+"_6 "+boxIdVal+"_7 = "+boxElectrodeRo.get(i).getSixRo());
            mNewsList.add(boxIdVal+"_7 "+boxIdVal+"_8 = "+boxElectrodeRo.get(i).getSevenRo());
            mNewsList.add(boxIdVal+"_8 "+boxIdVal+"_9 = "+boxElectrodeRo.get(i).getEightRo());
            mNewsList.add(boxIdVal+"_9 "+boxIdVal+"_10 = "+boxElectrodeRo.get(i).getNineRo());
            mNewsList.add(boxIdVal+"_10 "+boxIdVal+"_11 = "+boxElectrodeRo.get(i).getTenRo());
            mNewsList.add(boxIdVal+"_11 "+boxIdVal+"_12 = "+boxElectrodeRo.get(i).getElevenRo());
        }
        return mNewsList;
    }
    private Boolean writeObjectToExternalStorage(Context context, List<Object> list, String fileName,String itemName) {
        boolean bo = false;
        String path = DOWN_NAME+"shiwu/"+itemName;
        // 获取下载目录
        File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+"/shiwu/"+itemName);
        Gson gson = new Gson();
        String jsonString = gson.toJson(list);
        // 获取外部存储目录（公共文档目录）
        File file = new File(downloadsDir, fileName);
        File file1 = new File(path,fileName);
        if(!file.exists()){
            file.mkdir();
        }
        //for (int i = 0; i < list.size(); i++) {
        try (FileWriter writer = new FileWriter(file)) {
            // 写入对象
            writer.write(jsonString);
            Toast.makeText(context, "文件已保存到: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
            Log.d("文件已保存到: ",file.getAbsolutePath());
            bo = true;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.d("文件保存失败: ",e.getMessage());
        }
        //}
        return bo;
    }

    // Android 10+ 方法
//    @RequiresApi(api = Build.VERSION_CODES.Q)
//    private Boolean saveWithMediaStore(List<Object> list, String fileName,String itemName) {
//        boolean bo = false;
//        Gson gson = new Gson();
//        String content = gson.toJson(list);
//        ContentValues values = new ContentValues();
//        values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
//        values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
//        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS+"/shiwu/"+itemName);
//
//        ContentResolver resolver = getContentResolver();
//        Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
//
//        if (uri != null) {
//            try (OutputStream output = resolver.openOutputStream(uri);
//                 OutputStreamWriter writer = new OutputStreamWriter(output)) {
//                writer.write(content);
//                bo = true;
//                Toast.makeText(this, "文件已保存到 Download+"+"/shiwu/"+itemName+" 目录", Toast.LENGTH_SHORT).show();
//            } catch (IOException e) {
//                Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        }
//        return bo;
//    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    private Integer findItemCount() {
        itemsService = new ItemsService();
        List<Items> lis = itemsService.getItems(new Items());
        return lis.size();
    }

    private List<ElectrodeRoVo> performJoinQuery(String itemId) {
        int limit = (currentPage - 1) * pageSize;
        String type = "0";
        String status = "0";
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // SQL语句：查询用户表和订单表，根据用户ID关联
        Cursor cursor = db.query("tb_items ite left join tb_device dev on dev.item_id = ite.id left join tb_boxElectrodeRo ele on ele.item_id = ite.id ",
                new String[]{"ele.id, ite.name, ele.item_id, ite.operator, dev.sn as deviceId,ele.voltage as voltages, ele.create_time"},
                "ele.status = 0 and ite.id = ?",
                new String[]{itemId}, "ele.id", "", "ele.id DESC", String.valueOf(limit) + "," + String.valueOf(pageSize));
        System.out.println(cursor.getCount());
        List<ElectrodeRoVo> lis = new ArrayList<>();
        // 遍历结果集
        while (cursor.moveToNext()) {
            ElectrodeRoVo ElectrodeRoVo = new ElectrodeRoVo();
            String id = cursor.getString(0);
            ElectrodeRoVo.setId(id);
            String name = cursor.getString(1);
            ElectrodeRoVo.setName(name);
            int itemId1 = cursor.getInt(2);
            ElectrodeRoVo.setItemId(itemId1);
            String operator = cursor.getString(3);
            ElectrodeRoVo.setOperator(operator);
            String deviceId = cursor.getString(4);
            ElectrodeRoVo.setDeviceId(deviceId);
            String voltages = cursor.getString(5);
            ElectrodeRoVo.setVoltage(voltages);
            String create_time = cursor.getString(6);
            ElectrodeRoVo.setCreateTime(create_time);
            lis.add(ElectrodeRoVo);

            // 处理查询结果
            // ...
        }

        cursor.close();
        db.close();
        return lis;
    }

    public void updataData() {
        sendLisAll = new ArrayList<ElectrodeRoVo>();
        currentPage = 1;
        getDeviceLisAll();
        myAdapter.cleckAll();
    }

    public void getDeviceLisAll() {
        Resources res = getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);

        Items item = findSelectItem();
        //List<ElectrodeRoVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),0);
        List<ElectrodeRoVo> send = performJoinQuery(String.valueOf(item.getId()));
        currentPage += 1;
        sendLisAll.addAll(send);
        //创建一个simpleAdapter
        myAdapter = new ElectrodeRoAdapter(SendReceiveListActivity.this, sendLisAll,
                R.layout.electrode_list_item, modeData, freqData, repeatData, valtageData, this);
        //listView = findViewById(R.id.electrode_ro_list_view);
        listView.setAdapter(myAdapter);
    }

    private void getItemsDataHeaderPull() {
        Resources res = getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);
        Items item = findSelectItem();
        currentPage = 1;
        sendLisAll = null;
        sendLisAll = new ArrayList<ElectrodeRoVo>();
        //List<ElectrodeRoVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),0);
        List<ElectrodeRoVo> send = performJoinQuery(String.valueOf(item.getId()));
        currentPage += 1;
        sendLisAll.addAll(send);
        //创建一个simpleAdapter
        myAdapter = new ElectrodeRoAdapter(SendReceiveListActivity.this, sendLisAll, R.layout.electrode_list_item, modeData, freqData, repeatData, valtageData, this);
        //listView = findViewById(R.id.electrode_ro_list_view);
        listView.setAdapter(myAdapter);

    }

    private void getItemsDataFooterPull() {
        Resources res = getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);
        Items item = findSelectItem();
        //List<ElectrodeRoVo> deviceLis = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),0);
        List<ElectrodeRoVo> deviceLis = performJoinQuery(String.valueOf(item.getId()));
        if (deviceLis.size() > 0) {
            sendLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new ElectrodeRoAdapter(SendReceiveListActivity.this, sendLisAll, R.layout.electrode_list_item, modeData, freqData, repeatData, valtageData, this);
            currentPage++;
            myAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 全选
     *
     * @param
     */
    public void btnSelectAllList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
//
            checkBox = lin.findViewById(R.id.ele_list_items_checkbox);

            if (checkBox != null) {
                checkBox.setChecked(true);
            }
            checkSta = true;
//            did = lin.findViewById(R.id.ele_did);
//            String id = (String) did.getText();
//            ids += id + ",";

        }
    }

    /**
     * 全不选
     *
     * @param
     */
    public void btnNoList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
            checkSta = false;
//            did = lin.findViewById(R.id.ele_did);
//            String id = (String) did.getText();
//            ids += id + ",";
//            System.out.println("----ids----" + ids);
        }
        ids ="";
        updataData();
    }

    /**
     * 接口方法，响应ListView按钮点击事件
     */
    @Override
    public void clickListener(View v) {
        System.out.println("---------------------------v= " + v.getId());
        int id = v.getId();
        if (id > 0) {
            idlis.add(id);
        } else {
            String id1 = String.valueOf(id).substring(1);
            for (int i = 0; i < idlis.size(); i++) {
                if (idlis.get(i) == Integer.parseInt(id1)) {
                    idlis.remove(i);
                }
            }

        }
        System.out.println("---------------------------idlis= " + idlis);
        ids = "";
        for (int i = 0; i < idlis.size(); i++) {
            ids += idlis.get(i) + ",";
        }
        System.out.println("========ids ="+ids);
    }

    @Override
    public boolean clickRemoveListener(int position) {
        removeItemsDataUpdata(position);
        updateItem(position);
        return true;
    }

    private void removeItemsDataUpdata(int position) {
        Resources res = getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);
        Items item = findSelectItem();
        List<ElectrodeRoVo> deviceLis = boxElectrodeRoService.getAll((currentPage * 1), 1, item.getId(), 0);
        if (deviceLis.size() > 0) {
            sendLisAll.remove(position);
            sendLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new ElectrodeRoAdapter(SendReceiveListActivity.this, sendLisAll, R.layout.send_receive_list_item, modeData, freqData, repeatData, valtageData, this);
            //myAdapter.notifyDataSetChanged();
        }
    }

    private void updateItem(int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            myAdapter.getView(position, view, listView);
        }

    }
}